package dryven.model.validation.di;

import java.util.HashMap;
import java.util.Map;

import dryven.i18n.Translator;
import dryven.model.di.DependencyService;
import dryven.model.di.LocalThreadStorage;
import dryven.model.validation.DefaultValidatorSession;
import dryven.model.validation.MapErrorMessageCollection;
import dryven.model.validation.Validator;
import dryven.model.validation.ValidatorService;
import dryven.model.validation.ValidatorSession;
import dryven.model.validation.validators.DefaultValidator;

public class DependencyInjectingValidatorService implements ValidatorService {
	private DependencyService _diService;
	private Translator _tr;
	private Map<Class<? extends Validator>, Validator> _validatorCache = new HashMap<Class<? extends Validator>, Validator>();
	
	public DependencyInjectingValidatorService(DependencyService diService, Translator tr) {
		super();
		_tr = tr;
		_diService = diService;
	}

	public ValidatorSession newSession(LocalThreadStorage storage) {
		return new DefaultValidatorSession(this,_tr, storage);
	}

	@Override
	public Validator instanciateValidator(LocalThreadStorage storage,
			Class<? extends Validator> validatorType) {
		if(validatorType==null) {
			validatorType = DefaultValidator.class;
		}
		Validator v = _validatorCache.get(validatorType);
		if(v==null) {
			v = _diService.constructObject(storage, validatorType);
			_validatorCache.put(validatorType, v);
		}
		return v;
	}
}
